/*
 * Copyright (c) 2019 DawnFramework. All Rights Reserved.
 * Licensed under the MIT (LICENSE) license.
 */

package org.dawn.common.web.res;

import lombok.Getter;
import lombok.ToString;
import org.dawn.common.core.except.IError;

/**
 * 用于兼容 Controller 层返回统一数据模型的场景。建议异常码用 http status code 替代，Response body 直接返回 View 模型。
 *
 * @author Willard Hu on 2019-05-19.
 */
@Getter
@ToString
public class JsonResult {
    private Boolean success;
    private String code;
    private String message;
    private Object model;

    /** 屏蔽构造函数 */
    private JsonResult() {
    }

    public static Builder newBuilder() {
        return new Builder();
    }

    public static class Builder {
        private Boolean success;
        private String code;
        private String message;
        private Object model;

        /** 屏蔽构造函数 */
        private Builder() {
        }

        public Builder succ() {
            this.success = true;
            return this;
        }

        public Builder succ(Object model) {
            this.success = true;
            this.model = model;
            return this;
        }

        public Builder fail(String code, String message) {
            this.code = code;
            this.message = message;
            this.success = false;
            return this;
        }

        public Builder fail(IError<?> error) {
            this.code = String.valueOf(error.errcode());
            this.message = error.errmsg();
            this.success = false;
            return this;
        }

        public JsonResult build() {
            JsonResult res = new JsonResult();
            res.success = this.success;
            res.code = this.code;
            res.message = this.message;

            res.model = this.model;
            return res;
        }
    }
}
